﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.IO;

namespace BiHCurrencyConverter
{

    public partial class MainPage : PhoneApplicationPage
    {
        static List<string> Currencies = new List<string>();

        // Constructor

        public MainPage()
        {
            InitializeComponent();

            InitializeCurrencies();

            DataContext = Currencies;
        }

        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

        private void InitializeCurrencies()
        {
            foreach (var item in settings.Keys)
            {
                Currencies.Add(item.ToString());
            }
        }

        private void ListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            tbSrcValue.Text = lpSource.SelectedItem.ToString();
        }

        private void tbSrcValue_GotFocus(object sender, RoutedEventArgs e)
        {
            tbSrcValue.Text = "";
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            CalculateAmount();
        }

        private void CalculateAmount()
        {
            // var setup
            double numAmount = 0.0;
            double numResult = 0.0;
            double numSource = 0.0;
            double numDest = 0.0;
            object tempVar;

            // read exchange rates from IsolatedStorageSettings
            if (settings.TryGetValue((string)lpSource.SelectedItem, out tempVar))
            {
                numSource = (double)tempVar;
            }

            if (settings.TryGetValue((string)lpResulting.SelectedItem, out tempVar))
            {
                numDest = (double)tempVar;
            }

            // perform calculation
            numAmount = Convert.ToDouble(tbSrcValue.Text);
            numResult = (numDest / numSource) * numAmount;
            tbResult.Text = string.Format("{0:F2}", numResult);

        }

        PhoneApplicationService phoneAppService = PhoneApplicationService.Current;

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            phoneAppService.State["ValueToConvert"] = tbSrcValue.Text;
            base.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            object valToConvert;

            if (phoneAppService.State.ContainsKey("ValueToConvert"))
            {
                if (phoneAppService.State.TryGetValue("ValueToConvert", out valToConvert))
                {
                    tbSrcValue.Text = valToConvert.ToString();
                }
            }

            base.OnNavigatedTo(e);
        }

        private void btnRefreshData_Click(object sender, RoutedEventArgs e)
        {
            WebClient wc = new WebClient();
            wc.DownloadStringAsync(new Uri("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"));
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
        }

        IsolatedStorageFile fileStore = IsolatedStorageFile.GetUserStoreForApplication();

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            XDocument _doc = XDocument.Parse(e.Result);
            IsolatedStorageFileStream stream = new IsolatedStorageFileStream("eurofxref-daily.xml", FileMode.Truncate, FileAccess.ReadWrite, fileStore);
            try
            {
                StreamWriter writeFile = new StreamWriter(stream);
                _doc.Save(writeFile);
                writeFile.Close();
            }
            catch (Exception)
            {
                throw;
            }

            if (!settings.Contains("BAM"))
            {
                settings["BAM"] = 1.95583;
            }

            if (!settings.Contains("EUR"))
            {
                settings["EUR"] = 1.0;
            }

            IsolatedStorageFileStream streamRead = fileStore.OpenFile("eurofxref-daily.xml", FileMode.OpenOrCreate);

            try
            {
                XDocument dataDoc = XDocument.Load(streamRead);
                XNamespace gesmes = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";

                var quotes = from cube1 in dataDoc.Descendants(gesmes + "Cube")
                             from cube2 in cube1.Descendants(gesmes + "Cube")
                             from cube3 in cube2.Descendants(gesmes + "Cube")
                             select new ExchangeRates { Symbol = cube3.Attribute("currency").Value, Rate = double.Parse(cube3.Attribute("rate").Value) }; ;

                foreach (var item in quotes)
                {
                    settings[item.Symbol] = item.Rate;
                }
            }
            catch (Exception)
            {
                throw;
            }
            #region unused-code-comment
            //using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("eurofxref-daily.xml", FileMode.Open, fileStore))
            //{

            //    StreamReader readFile = new StreamReader(stream);
            //    _textIsolatedStorageReader = readFile.ReadToEnd();
            //    readFile.Close();
            //}
            #endregion

            MessageBox.Show("Succeeded");
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/About.xaml", UriKind.RelativeOrAbsolute));
        }


    }

    public class ExchangeRates
    {
        public string Symbol { get; set; }
        public double Rate { get; set; }

    }

}